﻿using ERPPublic;
using MediatR;
using Newtonsoft.Json;
using ProductionManagement.Application.Command.PickCommand;
using ProductionManagement.Domain.Dtos;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Dtos;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;
using static ERPPublic.ParseAPI;

namespace ProductionManagement.Application.CommandHandler.PickCommandHandlers
{
    public class SelectPickCommandHandlers : IRequestHandler<SelectPickCommand, PageDTO<SelectPickDTO>>
    {


        private readonly IPickRepository _pickRepository;
        private readonly IPickProductRepository _pickProductRepository;
        private readonly ISqlSugarClient db;


        public SelectPickCommandHandlers(IPickRepository pickRepository, IPickProductRepository pickProductRepository, ISqlSugarClient db)
        {
            _pickRepository = pickRepository;
            _pickProductRepository = pickProductRepository;
            this.db = db;
        }

        public async Task<PageDTO<SelectPickDTO>> Handle(SelectPickCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = await GetProductList("", "", 1, 100);
            var p = (from a in await _pickRepository.GetAll() select a).ToList();
            var pickpro = (from b in await _pickProductRepository.GetAll() select b).ToList();
           var list = (from a in p where a.IsDel==false select  new SelectPickDTO
            {
                PickingId = a.PickingId,
                PicNumber = a.PicNumber,
                PicCollarDate = a.PicCollarDate,
                PickNum = a.PickNum,
                PicTopic = a.PicTopic,
                PicNumTotal = a.PicNumTotal,
                 PickProList = (from c in pickpro
                               join f in p on c.PickingId equals f.PicNumber
                               join d in products on c.ProductId equals d.ProductId
                               where c.PickingId == a.PicNumber
                               select new SelectPickProDTO
                               {
                                   pName = d.PName,
                                   pNumber = d.PNumber,
                                   pSpec = d.PSpec,
                                   ManpowerId = c.ManpowerId,
                                   OutManager = c.OutManager,
                                   OutshipState = c.OutshipState,
                                   PickProductId = c.PickProductId,
                                   PickProductNum = c.PickProductNum,
                                   PickProductDelDate = c.PickProductDelDate,
                               }).ToList()
             
                               

            }).ToList();


            if (!string.IsNullOrEmpty(request.PickCode))
            {
                list = list.Where(x => x.PicNumber.Contains(request.PickCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PickToipc))
            {
                list = list.Where(x => x.PicTopic.Contains(request.PickToipc)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Sdate))
            {
                list = list.Where(x => x.PicCollarDate >= DateTime.Parse(request.Sdate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Edate))
            {
                list = list.Where(x => x.PicCollarDate <= DateTime.Parse(request.Edate)).ToList();
            }
            //if (request.OutState > 0)
            //{
            //    list = list.Where(x => x.OutshipState == request.OutState).ToList();
            //}



            int totalcount = list.Count();
            int pagecount = (int)Math.Ceiling(totalcount * 1.0 / request.pageSize);

            var dto = list.OrderByDescending(x => x.PickingId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();


            var page = new PageDTO<SelectPickDTO>
            {
                Totalcount = totalcount,
                Pagecount = pagecount,
                list = dto
            };
               return page;
        }



        /// <summary>
        /// 显示产品信息
        /// </summary>
        /// <param name="PName"></param>
        /// <param name="PNumber"></param>
        /// <param name="pindex"></param>
        /// <param name="psize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetProductList(string? PName, string? PNumber, int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MSIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTkiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5bCP576OIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.ZjkGj2IxuBzKmF5ZuSyWXQW8TkVqBGLUDkJ86RSweFI";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/erpcp/api/Product/ProductShow?PName=" + PName + "&PNumber=" + PNumber + "&ProductTypeId=" + 0 + "&PageIndex=" + pindex + "&PageSize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }



        //产品
        public class Products
        {
            /// <summary>
            /// 产品Id
            /// </summary>
            [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
            public int ProductId { get; set; }
            /// <summary>
            /// 标识
            /// </summary>

            public int? PCharacteristic { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PNumber { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PName { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PSpec { get; set; }
            /// <summary>
            /// 单位
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PUnit { get; set; }

            /// <summary>
            /// 产品分类ID
            /// </summary>

            public int ProductTypeId { get; set; }


        }

    }
}
